package com.jeesite.modules.app.course;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.entity.Page;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.modules.app.course.exercise.record.entity.TcourseExerciseRecord;
import com.jeesite.modules.app.course.exercise.record.service.TcourseExerciseRecordService;
import com.jeesite.modules.app.topic.conversation.entity.ApptopicOfConversation;
import com.jeesite.modules.app.topic.conversation.service.ApptopicOfConversationService;
import com.jeesite.modules.app.user.entity.AppUser;
import com.jeesite.modules.app.user.service.AppUserService;
import com.jeesite.modules.conf.AppController;
import com.jeesite.modules.conf.MessageCode;
import com.jeesite.modules.conf.RedisUtils;
import com.jeesite.modules.sys.entity.Area;
import com.jeesite.modules.sys.service.AreaService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.zx.course.authorization.entity.TcourseAuthorization;
import com.jeesite.modules.zx.course.authorization.service.TcourseAuthorizationService;
import com.jeesite.modules.zx.course.buy.record.entity.TcourseBuyRecord;
import com.jeesite.modules.zx.course.buy.record.service.TcourseBuyRecordService;
import com.jeesite.modules.zx.course.entity.Tcourses;
import com.jeesite.modules.zx.course.exercises.user.entity.TcourseExercisesUser;
import com.jeesite.modules.zx.course.exercises.user.service.TcourseExercisesUserService;
import com.jeesite.modules.zx.course.service.TcoursesService;
import com.jeesite.modules.zx.customer.credit.details.entity.TcustomerCreditDetails;
import com.jeesite.modules.zx.customer.credit.details.service.TcustomerCreditDetailsService;
import com.jeesite.modules.zx.customer.exercises.entity.TcustomerExercises;
import com.jeesite.modules.zx.customer.exercises.service.TcustomerExercisesService;
import com.jeesite.modules.zx.customer.points.details.entity.TcustomerPointsDetails;
import com.jeesite.modules.zx.customer.points.details.service.TcustomerPointsDetailsService;
import com.jeesite.modules.zx.sys.msg.push.entity.ZxMsgPush;
import com.jeesite.modules.zx.sys.msg.push.service.ZxMsgPushService;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 课程中心
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/app/course/tcourses/")
public class AppCourseController {
		@Autowired
		private TcoursesService tcoursesService;
		@Autowired
		private AppUserService appUserService;
		@Autowired
		private TcustomerExercisesService tcustomerExercisesService;
		@Autowired
		private ApptopicOfConversationService apptopicOfConversationService;
		@Autowired
       	private ZxMsgPushService zxMsgPushService;
		@Autowired
		private TcustomerPointsDetailsService tcustomerPointsDetailsService;
		@Autowired
		private TcustomerCreditDetailsService tcustomerCreditDetailsService;
		@Autowired
		private TcourseBuyRecordService tcourseBuyRecordService;
		@Autowired
		private TcourseExercisesUserService tcourseExercisesUserService;
		@Autowired
		private TcourseExerciseRecordService tcourseExerciseRecordService;
		@Autowired
		private TcourseAuthorizationService tcourseAuthorizationService;
		@Autowired
		private RedisUtils redisUtils;
		/**
		 * 查询课程的所有分类和推荐课程
		 * @param request
		 * @param response
		 */
	    @RequestMapping(value = "class")
        public void getClass(HttpServletRequest request,HttpServletResponse response){
        	String json=DictUtils.getDictListJson("t_course_item_query");
        	//去掉课程推荐
        	JSONArray array = JSONObject.parseArray(json);
			for(int i=0 ; i < array.size() ;i++){
				JSONObject  object = array.getJSONObject(i);
				String dictValue = (String) object.get("dictValue");
				if ("1".equals(dictValue)){
					array.remove(object);
				}
			}
        	Tcourses tcourses=new Tcourses();
        	tcourses.setCourseItem("2");//设置人民币
        	tcourses.setParentCode("0");
        	tcourses.setPage(new Page<>(request, response));
			Page<Tcourses> findPage = tcoursesService.findPage(tcourses);
		    JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
			JSONObject jsonObje=new JSONObject();
			jsonObje.put("items", array);
			jsonObje.put("course", parseObject);
        	AppController.renderSuccessObject(response, jsonObje, MessageCode.SUCCESS_ACK);
        }
	    /**
	     * 分页查询
	     */
	    @RequestMapping(value = "findPage")
	    public void findPage(Tcourses tcourses,HttpServletRequest request,HttpServletResponse response){
	    	tcourses.setPage(new Page<>(request,response));
	    	Page<Tcourses> findPage = tcoursesService.findPage(tcourses);
		    JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
		    AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	    }
	    /**
	     * 列表查询
	     */
	    @RequestMapping(value = "findList")
	    public void findList(Tcourses tcourses,HttpServletRequest request,HttpServletResponse response){
	    	List<Tcourses> findList = tcoursesService.findList(tcourses);
		    JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		    AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	    }
	    /**
	     * 根据分类值查询课程
	     * @param request
	     * @param response
	     */
	    @RequestMapping(value = "item")
	    public void item(Tcourses tcourses,HttpServletRequest request,HttpServletResponse response){
	    	String item=request.getParameter("item");
	    	if(StringUtils.isBlank(item)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "分类标识");
	    		return;
	    	}
	    	String courseTitle=request.getParameter("courseTitle");
	    	tcourses.setParentCode("0");
	    	if(StringUtils.isBlank(courseTitle)){
	    	    tcourses.setCourseTitle(courseTitle);
	    	}
	    	tcourses.setCourseItem(item);
	    	tcourses.setPage(new Page<>(request, response));
	    	Page<Tcourses> findPage = tcoursesService.findPage(tcourses);
	    	JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
	    	AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);	    	
	    }
	    /**
	     * 首页数据
	     * @param request
	     * @param response
	     */
	    @RequestMapping(value="homeData")
	    public void homeData(HttpServletRequest request,HttpServletResponse response){
	    	String item=request.getParameter("item");
	    	if(StringUtils.isBlank(item)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "分类标识");
	    		return;
	    	}
	    	Tcourses tcourses=new Tcourses();
	    	tcourses.setParentCode("0");
//	    	tcourses.setCourseItem(item);
	    	tcourses.setRecommend(1);
	    	List<Tcourses> coursesList = tcoursesService.findList(tcourses);
//	    	ApptopicOfConversation topic=new ApptopicOfConversation();
//	    	topic.setHotOrRecomm(Integer.parseInt(item));
//	    	List<ApptopicOfConversation> topicList = apptopicOfConversationService.findList(topic);
	    	List<ApptopicOfConversation> topicList=new ArrayList<ApptopicOfConversation>();
	    	JSONArray coursesArray = JSONObject.parseArray(JsonMapper.toJson(coursesList));
	    	JSONArray topicArray = JSONObject.parseArray(JsonMapper.toJson(topicList));
	    	JSONObject json=new JSONObject();
	    	json.put("coursesArray", coursesArray);
	    	json.put("topicArray", topicArray);
	    	String userId=request.getParameter("userId");
	    	if(StringUtils.isNotBlank(userId)) {
	    		Object sessionKey=redisUtils.get(userId);
	    		json.put("sessionKey", sessionKey);
	    	}
	    	AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
	    }
	    /**
	     * 查询课程的课时
	     * @param request
	     * @param response
	     */
	    @RequestMapping(value="detail")
	    public void detail(HttpServletRequest request,HttpServletResponse response){
	    	String id=request.getParameter("id");
	    	if(StringUtils.isBlank(id)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "数据标识");
	    		return;
	    	}
	    	Tcourses tcourses=new Tcourses();
	    	tcourses.setParentCode(id);
	    	tcourses.setCourseExplain(1);
	    	List<Tcourses> findList = tcoursesService.findList(tcourses);
	    	TcourseBuyRecord tbr=null;
	    	String userId=request.getParameter("userId");
	    	for(Tcourses t:findList){
	    		Double coursePrice = t.getCoursePrice();
	    		if(coursePrice>0){
	    			if(StringUtils.isBlank(userId)){
	    				t.setRemarks(null);
	    				continue;
	    			}
		    		tbr=new TcourseBuyRecord();
		    		tbr.setCourseId(id);
		    		String courseHoursId=t.getId();
		    		tbr.setCourseHoursId(courseHoursId);
		    		tbr.setUserId(userId);
		    		long findCount = tcourseBuyRecordService.findCount(tbr);
		    		if(findCount>0){
		    			continue;
		    		}else{
		    			t.setRemarks(null);
		    		}
	    		}
	    	}
	    	tcourses = tcoursesService.get(id);
	    	tcourses.setChildList(findList);
	    	if(tcourses==null){
	    		AppController.renderErrorString(response, MessageCode.DB_DATA_SAC_ERROR, "数据不存在");
	    		return;
	    	}
	    	JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(tcourses));
	    	AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	    }
	    /**
	     * 查看课时详情
	     * @param request
	     * @param response
	     */
	    @RequestMapping(value="courseHours")
	    public void courseHose(HttpServletRequest request,HttpServletResponse response){
	    	String id=request.getParameter("id");
	    	if(StringUtils.isBlank(id)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "数据标识");
	    		return;
	    	}
	    	Tcourses tcourses = tcoursesService.get(id);
	    	Double coursePrice = tcourses.getCoursePrice();
	    	if(coursePrice!=null && coursePrice>0){
		    	String userId=request.getParameter("userId");
		    	if(StringUtils.isNotBlank(userId)){
		    		TcourseAuthorization entity=new TcourseAuthorization();
		    		String parentCode = tcourses.getParentCode();
		    		entity.setCourseId(parentCode);
		    		entity.setUserId(userId);
					List<TcourseAuthorization> findList = tcourseAuthorizationService.findList(entity);
					if(findList!=null && findList.size()>0){
						
					}else{
						TcourseBuyRecord tbr=new TcourseBuyRecord();
			    		tbr.setCourseId(parentCode);
			    		tbr.setCourseHoursId(id);
			    		tbr.setUserId(userId);
			    		Long findCount = tcourseBuyRecordService.findCount(tbr);
			    		if(findCount!=null&&findCount>0){
			    		}else{
			    			tcourses.setRemarks(null);
			    		}
					}
		    	}else{
		    		tcourses.setRemarks(null);
		    	}
	    	}
	    	String teacherId=request.getParameter("teacherId");
	    	if(StringUtils.isNotBlank(teacherId)){
	    		AppUser user=new AppUser();
		    	user.setUserCode(teacherId);
		    	List<AppUser> findList = appUserService.findList(user);
		    	if(tcourses!=null){
		    		if(findList!=null){
		    			if(findList.size()>0){
		    				tcourses.setAppUser(findList.get(0));		
		    			}
		    		}	    	   
		    	}
	    	}	    	
	    	JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(tcourses));
	    	AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	    }
	    /**
	     * 查询课时的练习题
	     * @param args
	     */
	    @RequestMapping(value="exercises")
	    public void exercises(HttpServletRequest request,HttpServletResponse response){
	    	String parentCode=request.getParameter("parentCode");
	    	if(StringUtils.isBlank(parentCode)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "查询标识");
	    		return;
	    	}
	    	Tcourses tcourse=new Tcourses();
	    	tcourse.setParentCode(parentCode);
	    	List<Tcourses> findList = tcoursesService.findList(tcourse);
    		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
    		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
    		return;
	    }

	/**
	 * 查询课时的练习题
	 * @param
	 */
	@RequestMapping(value="exercisesNew")
	public void exercisesNew(HttpServletRequest request,HttpServletResponse response){
		//获取所有数据直接吐给前台
		String parentCode=request.getParameter("parentCode");
		Tcourses tcourse=new Tcourses();
		tcourse.getSqlMap().getWhere().andBracket("id", QueryType.EQ, parentCode, 1)
				.or("parent_codes", QueryType.LEFT_LIKE, ","+parentCode+",%", 2).endBracket();
		tcourse.getSqlMap().getOrder().setOrderBy("id asc");
		List<Tcourses> findList = tcoursesService.findList(tcourse);
		//treeLevel 2 标题  treeLevel  3 是问题   treeLevel 4是选项
		List<Tcourses> subjectList = null;
		long maxSize = 0;
		Map<String,Object> map = new HashMap<>();
		if (findList.size()>0){
			maxSize = findList.stream().filter(e->(e.getTreeLevel()==3)).count();
			subjectList = findList.stream().filter(e->(e.getParentCode().equals(parentCode))).collect(Collectors.toList());
			for (Tcourses tcourses:subjectList){
				List<Tcourses>  questList = findList.stream().filter(e->(e.getParentCode().equals(tcourses.getId()))).collect(Collectors.toList());
				tcourses.setChildList(questList);
				for (Tcourses quest:questList){
					List<Tcourses>  optionList = findList.stream().filter(e->(e.getParentCode().equals(quest.getId()))).collect(Collectors.toList());
					//赋值答案给问题
					if (optionList.size()>0){
						quest.setAnswerStr(getAnswerStr(optionList));
					}
					quest.setChildList(optionList);
				}
			}
		}
		map.put("maxSize",maxSize);
		map.put("data",subjectList);
		AppController.renderSuccessObject(response, JsonMapper.toJson(map), MessageCode.SUCCESS_ACK);
		return;
	}

	private String getAnswerStr(List<Tcourses>  optionList ){
		String[] arr = new String[]{"A","B","C","D","E"};
		String answerStr = "";
		List<String>  answerOptionIds = optionList.stream().filter(e->e.getAnswer()!=null&&e.getAnswer()==1).map(e->e.getId()).collect(Collectors.toList());
		for (int i=0;i<optionList.size();i++){
			String id = optionList.get(i).getId();
			if (answerOptionIds.contains(id)){
				answerStr = answerStr+arr[i]+",";
			}
		}
		if (StringUtils.isNotBlank(answerStr)){
			answerStr = answerStr.substring(0,answerStr.length()-1);
		}
		return  answerStr;
	}
	/**
	 * 查询课时的练习题的选项
	 * @param args
	 */
	@RequestMapping(value="exercisesOptions")
	public void exercisesOptions(HttpServletRequest request,HttpServletResponse response){
		String parentCode=request.getParameter("parentCode");
		if(StringUtils.isBlank(parentCode)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "查询标识");
			return;
		}
		Tcourses questTcourse = tcoursesService.get(parentCode);
		Tcourses tcourse=new Tcourses();
		tcourse.setParentCode(parentCode);
		tcourse.getSqlMap().getOrder().setOrderBy("id asc");
		List<Tcourses> findList = tcoursesService.findList(tcourse);
		Map<String,Object> map = new HashMap<>();
		if (findList.size()>0){
			map.put("answer",findList.stream().filter(e->e.getAnswer()!=null&&e.getAnswer()==1).collect(Collectors.toList()));
		}
		map.put("data",findList);
		map.put("objType",questTcourse.getCourseItem());

		//JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(map));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
		return;
	}
	    /**
	     * options
	     * @param request
	     * @param response
	     */
	    @RequestMapping(value="options")
	    public void options(HttpServletRequest request,HttpServletResponse response){
	    	String userId=request.getParameter("userId");
	    	if(StringUtils.isBlank(userId)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
	    		return;
	    	}
	    	String parentCode=request.getParameter("parentCode");
	    	if(StringUtils.isBlank(parentCode)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "查询标识");
	    		return;
	    	}
	        String courseId=request.getParameter("courseId");
	        if(StringUtils.isBlank(courseId)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "课程标识");
	    		return;
	    	}
	    	TcourseExerciseRecord record=new TcourseExerciseRecord();
	    	record.setUserId(userId);
	    	record.setQuestionId(parentCode);
	    	record.setCourseId(courseId);
	    	List<TcourseExerciseRecord> recordList=tcourseExerciseRecordService.findList(record);
//	    	Map<String,TcourseExerciseRecord> map=new HashMap<String, TcourseExerciseRecord>();
	    	List<String> list=new ArrayList<>();
	    	for(TcourseExerciseRecord anwer:recordList){
				String answerId = anwer.getAnswerId();
				for(String key:answerId.split(",")){
				  if(StringUtils.isNotBlank(key)){
					list.add(key);
				  }
				}
	    	}
	    	Tcourses tcourse=new Tcourses();
	    	tcourse.setParentCode(parentCode);
            tcourse.getSqlMap().getOrder().setOrderBy("id asc");
	    	List<Tcourses> findList = tcoursesService.findList(tcourse);
	    	for(Tcourses course:findList){
	    		String id = course.getId();
	    		if(list.contains(id)){
	    			course.setChecked(true);
	    		}
	    	}
	    	JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
    		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
    		return;
	    }
	    @RequestMapping(value="userExercises")
	    public void userExercises(HttpServletRequest request,HttpServletResponse response){	    	
	    	String userId=request.getParameter("userId");
	    	if(StringUtils.isBlank(userId)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
	    		return;
	    	}
	    	String courseId=request.getParameter("courseId");
	    	if(StringUtils.isBlank(courseId)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "课程标识");
	    		return;
	    	}
	    	String exercisesId=request.getParameter("exercisesId");
	    	if(StringUtils.isBlank(exercisesId)){
	    		AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "练习记录标识");
	    		return;
	    	}
	    	String courseHourseId=request.getParameter("courseHourseId");
			if(StringUtils.isBlank(courseHourseId)){
				AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "课时标识");
				return;
			}
	    	TcourseExerciseRecord ter=new TcourseExerciseRecord();
	    	ter.setCourseHourseId(courseHourseId);
	    	ter.setCourseId(courseId);
	    	ter.setUserId(userId);
	    	List<TcourseExerciseRecord> findList = tcourseExerciseRecordService.findList(ter);
	    	BigDecimal success=new BigDecimal(0.0);
	        int error=0;
	        int record=findList.size();
	        if(findList!=null&&findList.size()>0){
	        	for(TcourseExerciseRecord terecord:findList){
					String questionId = terecord.getQuestionId();
					BigDecimal score=terecord.getScore();
					success=success.add(score);	        		
	        	}
	        }
	    	TcourseExercisesUser tcourseExercisesUser = new TcourseExercisesUser();
	    	tcourseExercisesUser.setId(exercisesId);
	    	tcourseExercisesUser.setState(4);
	    	tcourseExercisesUser.setBarbecueEdtime(new Date());
	    	tcourseExercisesUser.setScore(success);
	    	tcourseExercisesUserService.update(tcourseExercisesUser);
	    	JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(tcourseExercisesUser));
	    	AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	    }


	//临时为了审核通过 做了轮播的
	//在后续的处理中都会有这个标志来控制审核的所有页面
	//true 代表是要给客户看的真正内容，false表示需要隐藏，为了审核
	@Value("${audit.flag}")
	boolean auditFlag;


	@RequestMapping(value = "changeList")
	@ResponseBody
	public void  changeIndexImage(HttpServletRequest request,HttpServletResponse response){
		List<String> list = new LinkedList<>();

		if(auditFlag==false){
			list.add("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2763523135,381182796&fm=26&gp=0.jpg");
			list.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1587726846541&di=c7c5eb03e02fff3a03a5a8e1a460a9df&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201510%2F20%2F20151020194029_wcySK.jpeg");

		}else{
			list.add("https://bjhylfkj.oss-cn-beijing.aliyuncs.com/knowing/20200329/fccp.png");
			list.add("https://bjhylfkj.oss-cn-beijing.aliyuncs.com/knowing/20200329/2020xx.png");
			list.add("https://bjhylfkj.oss-cn-beijing.aliyuncs.com/knowing/20200329/banner1.jpeg");
			list.add("https://bjhylfkj.oss-cn-beijing.aliyuncs.com/knowing/20200329/banner2.jpeg");
			list.add("https://bjhylfkj.oss-cn-beijing.aliyuncs.com/knowing/20200329/banner3.jpg");
		}
		Map<String,Object> map = new HashMap<>();

		map.put("audFlag", auditFlag);
		map.put("data",list);

		AppController.renderSuccessObject(response, map, MessageCode.SUCCESS_ACK);


	}


	    public static void main(String[] args) {
	        String astr="1,2,3,4,4,5,4,,4,2,4,,,2,3,3,,2,3,23";
	        String[] split = astr.split(",");
	        for(String key:split){
	        	if(StringUtils.isBlank(key)){
	        		continue;
	        	}
	        	System.out.println(key);
	        }
		}
}
